package com.yxh.lib_base.util.router

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment

/**
 * @作者：yuan_xh
 * @时间：2022/8/15 20:27
 * @描述： 路由
 **/

fun Any?.navigationToAc(
    activityName: String, requestCode: Int = -1,param: (Bundle.() -> Unit)? = null
) {
    var bundle = param.takeIf { it != null }?.run {
        val bundle = Bundle()
        invoke(bundle)
        bundle
    }
    RouterUtils.startActivity(this, activityName, bundle,requestCode)
}

fun navigationToAc(activityName: String, param: (Bundle.() -> Unit)? = null) {
    var bundle = param.takeIf { it != null }?.run {
        val bundle = Bundle()
        invoke(bundle)
        bundle
    }
    RouterUtils.startActivity(null, activityName, bundle)
}

object RouterUtils {

    fun init(context: Context) = RouterImpl.init(context)

    /**
     * 启动 Activity
     * @param activityName Activity 名，例如 "TUIGroupChatActivity"
     * @param param 传给 Activity 的参数
     */
    fun startActivity(activityName: String, param: Bundle? = null) {
        startActivity(null, activityName, param, -1)
    }

    /**
     * 启动 Activity
     * @param starter 启动者，可以是 [Context]，也可以是 [Fragment]
     * @param activityName Activity 名，例如 "TUIGroupChatActivity"
     * @param param 传给 Activity 的参数
     */
    fun startActivity(starter: Any?, activityName: String, param: Bundle?) {
        startActivity(starter, activityName, param, -1)
    }

    /**
     * 启动 Activity
     * @param starter 启动者，可以是 [Context]，也可以是 [Fragment]
     * @param activityName Activity 名，例如 "TUIGroupChatActivity"
     * @param param 传给 Activity 的参数
     * @param requestCode 传给 Activity 的请求值，用来在 Activity 结束时在启动者的 onActivityResult 方法中返回结果，大于等于 0 有效。
     */
    fun startActivity(starter: Any?, activityName: String, param: Bundle?, requestCode: Int) {
        val navigation = RouterImpl.instance.setDestination(activityName).putExtras(param)
        when (starter) {
            is Fragment -> {
                navigation.navigate(starter as Fragment?, requestCode)
            }
            is Context -> {
                navigation.navigate(starter as Context?, requestCode)
            }
            is View ->{
                navigation.navigate(starter.context, requestCode)
            }
            else -> {
                navigation.navigate(null as Context?, requestCode)
            }
        }
    }
}

